package org.example.tialsproject.filter;


import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.tialsproject.pojo.ResponseResult;
import org.example.tialsproject.utils.JwtUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*") // 拦截所有请求
//@WebFilter(urlPatterns = "/user/login")// 拦截登录请求
//@WebFilter(urlPatterns = "/emps/*")// 拦截emps下的所有请求
public class DemoFilter implements Filter {
    /*
     * 初始化的时候执行，调用一次
     * */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /*
     * 销毁的时候执行，调用一次
     * */
    @Override
    public void destroy() {
        Filter.super.destroy();

    }

    /*
     *拦截到请求之后执行，调用多次
     * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String url = req.getRequestURI();
        if (url.contains("/user/login")) {
            /*放行本次请求*/
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            String jwt = req.getHeader("token");
            if (!StringUtils.hasLength(jwt)) {
                ResponseResult error = ResponseResult.error("请登录");
                String jsonString = JSONObject.toJSONString(error);
                res.getWriter().write(jsonString);
                return;
            } else {
                try {
                    JwtUtils.parseJwt(jwt);
                } catch (Exception e) {
                    ResponseResult error = ResponseResult.error("请登录");
                    String jsonString = JSONObject.toJSONString(error);
                    res.getWriter().write(jsonString);
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
